package com.yfuxdeer.youchat.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    private static SimpleDateFormat dateFormat;

    static {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    }

    public static Date getDate(String date) {
        try {
            return dateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getDate(Date date) {
        Date now = new Date();
        now.setHours(0);
        now.setMinutes(0);
        now.setSeconds(0);
        //当天的仅返回时间
        if (date.after(now)) {
            return dateFormat.format(date).split(" ")[1];
        }

        //昨天的返回昨天
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1); //得到昨天的时间
        Date yesterday = calendar.getTime();
        yesterday.setHours(0);
        yesterday.setMinutes(0);
        yesterday.setSeconds(0);
        if (date.after(yesterday)) {
            return "昨天";
        }

        //今年的就返回日期+时间
        if (date.getYear() == now.getYear()) {
            String[] strings = dateFormat.format(date).split("-");
            return strings[1] + "-" + strings[2];
        }

        //否则只返回日期
        return dateFormat.format(date).split(" ")[0];
    }

}
